<template>
	<om-addpage :menuList='menuList' :showChooseBtn="ismenu"  style="padding-top: 35px;" :checkedit="checkedit" :menuName="menuName" @formSubmit="formSubmit" :busCode="busCode">
		<om-autoform ref="autoform" :checkedit="checkedit" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		errorModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		hasEditor,
		getEditorTitle,
		changeConfigAttr,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';

	export default {
		data() {
			return buildFormData({
				communicateUserIdCache:'aft-bx-serviceCommunication-communicateUserId-cache',
				businessOwnerCache:'aft-bx-serviceCommunication-businessOwner-cache',
				customerCache:'aft-bx-serviceCommunication-customer-cache',
				checkedit:false,
				ismenu:false,
				menuList:[]
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId','salaryInstId','salaryInstName'])
		},
		provide() {
			return {
				formPage: this
			}
		},
		methods: {
			findInstByUserIdOrPostId(id){
				let _that = this
				_that.om.request(
					"orgInstPosUserOfficial/findInstByUserIdOrPostId",
					{
						userId:id
					}
				).then(res=>{
						_that.$refs.autoform.changeEditor("title",'communicateInstId',"data",configSelectData(res,'id','instName'))
						_that.$refs.autoform.initSelectIndex("title",'communicateInstId')
				})
			},
			clearCommunicateUser(){
				let _that = this
				_that.$refs.autoform.clear("title","communicateUserId")
				_that.$refs.autoform.clear("title","communicateInstId")
				_that.$refs.autoform.changeEditor("title",'communicateInstId',"data",configSelectData([],'id','instName'))
			},
			onselectCommunicateResultId(item){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				if(_that.subEditorObj['title1']){
					let dataList = _that.subEditorObj['title1'].workList
					for(let index in dataList){
						dataList[index].communicateResultId = item.id
						dataList[index].communicateResultName = item.text
					}
					formdata.dataStr = JSON.stringify(dataList)
					if(_that.subEditorObj['title1']){
						_that.subEditorObj['title1'].workList = dataList
					}
					uni.setStorageSync('oldWorkList', JSON.stringify(dataList))
					_that.om.toast('子表数据已更新')
				}
			},
			onselectLateServiceTypeId(item){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				if(_that.subEditorObj['title1']){
					let dataList = _that.subEditorObj['title1'].workList
					for(let index in dataList){
						dataList[index].lateServiceTypeId = item.id
						dataList[index].lateServiceTypeName = item.text
					}
					formdata.dataStr = JSON.stringify(dataList)
					if(_that.subEditorObj['title1']){
						_that.subEditorObj['title1'].workList = dataList
					}
					uni.setStorageSync('oldWorkList', JSON.stringify(dataList))
					_that.om.toast('子表数据已更新')
				}
			},
			onSubChange(editor){
				let _that = this.$refs.autoform
				if(editor.workList.length) {
					let oldWorkListStr = uni.getStorageSync("oldWorkList");
					let oldWorkListArr = JSON.parse(oldWorkListStr)
					if(oldWorkListArr.length == editor.workList.length){
						for(let i=0; i<editor.workList.length; i++){
							if(editor.workList[i].communicateResultId != oldWorkListArr[i].communicateResultId){
								_that.clear("title","communicateResultId")
							}
							if(editor.workList[i].lateServiceTypeId != oldWorkListArr[i].lateServiceTypeId){
								_that.clear("title","lateServiceTypeId")
							}
						}
					}else if(oldWorkListArr.length < editor.workList.length){
						for(let i=0; i<editor.workList.length;i++){
							if(_that.formdata.communicateResultId != editor.workList[i].communicateResultId){
								_that.clear("title","communicateResultId")
							}
							if(_that.formdata.lateServiceTypeId != editor.workList[i].lateServiceTypeId){
								_that.clear("title","lateServiceTypeId")
							}
						}
					}else{
						
					}
					uni.setStorageSync('oldWorkList', JSON.stringify(editor.workList))
				}
			},
			clearCustomerId(){
				let _that = this
				_that.$refs.autoform.clear("title2","customerId")
				_that.$refs.autoform.clear("title2","customerName")
			},
			clearBusinessOwnerId(){
				let _that = this
				_that.$refs.autoform.clear("title2","businessOwnerId")
				_that.$refs.autoform.clear("title2","businessInstId")
				_that.$refs.autoform.changeEditor("title2","businessInstId","data",configSelectData([],"id","salaryPosInstName"))
			},
			getWorkParam(){
				let _that = this
				let title = _that.$refs.autoform.getEditorTitle("title","repairReportTime")
				return {
					title:title,
					repairReportTime:_that.$refs.autoform.formdata.repairReportTime,
					communicateResultId:_that.$refs.autoform.formdata.communicateResultId,
					communicateResultName:_that.$refs.autoform.formdata.communicateResultName,
					lateServiceTypeId:_that.$refs.autoform.formdata.lateServiceTypeId,
					lateServiceTypeName:_that.$refs.autoform.formdata.lateServiceTypeName
				}
			},
			clearCustomerContact(){
				let _that = this
				_that.$refs.autoform.clear("title","customerContactId")
				_that.$refs.autoform.clear("title","customerContactPhone")
			},
			clearCustomer(){
				let _that = this
				_that.$refs.autoform.clear("title","customerId")
				_that.$refs.autoform.clear("title","customerName")
				_that.$refs.autoform.clear("title","customerContactId")
				_that.$refs.autoform.clear("title","customerContactPhone")
			},
			clearBusinessOwner(){
				let _that = this
				_that.$refs.autoform.clear("title","businessOwnerId")
				_that.$refs.autoform.clear("title","businessInstId")
			},
			clearRepairReportUser(){
				let _that = this
				_that.$refs.autoform.clear("title","repairReportUserId")
				_that.$refs.autoform.clear("title","repairReportInstId")
				
			},
			getInstData(userId){
				let _that = this
				return _that.om.request(
					'orgInstPosUserOfficial/findInstByUserIdOrPostId',
					{
						userId: userId
					}
				)
			},
			async findInstByUserIdOrPostId1(id){
				let _that = this
				return await _that.getInstData(id)
			},
			onselectRequiredCompleteDate(data){
				let _that = this
				if (new Date(data).getTime() < new Date().getTime() - 24 * 60 * 60 * 1000) {
					errorModal(_that,'提示信息',"“要求完成日期”要大于等于当前日期，请重新选择！",()=>{
						_that.$refs.autoform.clear("title",'requiredCompleteDate')
					})
				}
			},
			verifyCustomerContact(){
				let _that = this
				if(_that.$refs.autoform.formdata.customerId){
					return true
				}else{
					let title1 = _that.$refs.autoform.getEditorTitle("title")
					let title = _that.$refs.autoform.getEditorTitle("title","customerId")
					errorModal(_that,'提示信息',title1+'中的'+title+'需要优先编辑',()=>{})
					return false
				}
			},
			getCustomerData(id){
				let _that = this
				_that.$refs.autoform.changeEditor("title","customerContactId",{
					link:'../../public/pageSearch/pageSearch',
					"linkParam":{
						other:JSON.stringify({
							customerShowId: id
						}),
						url:'customerShow/getCustomerData',
						namefield:'userName',
						notefield:'phone',
						initload:true,
						searchfield:'q',
						cachename:_that.customerContactCache
					}
				})
			},
			initLoad(options) {
				let _that = this;
				var fileId = options.fileId
				let ajaxArr = [
					urlUtil.zposUrl(options.code), //制表岗位
					{
						url:'orgInstPosUserOfficial/findInstByUserIdOrPostId',
						param:{
							userId: _that.userId
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8820'
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'7592'
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8823'
						}
					},
					{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8826'
						}
					},
{
						url:'dictSource/loadCombo',
						param:{
							sourceId:'289',
							categoryId:'8823'
						}
					},
					{
						url:'common/getMenu',
						param:{
							formCode:options.code
						},
					}
				]
				if(fileId){
					ajaxArr.push({
						url:'serviceCommunication/getValue',
						param:{
							fileId:fileId
						}
					})
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					changeEditor("topinfo",'zinstId',{
						defaultValue:_that.salaryInstId,
						defaultName:_that.salaryInstName
					},null,mainData)
					changeEditor("title",'communicateTime', 'noInitDate',true,mainData)
					_that.menuList =  res[7].value
					changeEditor("title",'communicateResultId', 'data', configSelectData(res[6], 'id', 'text'), mainData);
					changeEditor("title2",'businessInstId', 'data', configSelectData([], 'id', 'salaryPosInstName'), mainData);
					changeEditor("title",'communicateWayId', 'data', configSelectData(res[3], 'id', 'text'), mainData);
					changeEditor("title",'communicateResultId', 'data', configSelectData(res[4], 'id', 'text'), mainData);
					changeEditor("title",'lateServiceTypeId', 'data', configSelectData(res[5], 'id', 'text'), mainData);
					changeEditor('title',"communicateUserId",{
						link:'../../public/searchUser/searchUser',
						"linkParam":{
							cachename: _that.communicateUserIdCache,
							isSingle:true
						}
					},null,mainData)
					changeEditor("title2","businessOwnerId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify({
								
							}),
							url:'temployee/getStaffCombogrid',
							namefield:'userPosInstName',
							initload:true,
							searchfield:'q',
							cachename:_that.businessOwnerIdCache
						}
					},null,mainData)
					changeEditor("title2","customerId",{
						link:'../../public/pageSearch/pageSearch',
						"linkParam":{
							other:JSON.stringify({
								
							}),
							url:'customerShow/getCustomerPageTwo',
							namefield:'customerName',
							notefield:'customerId',
							initload:true,
							searchfield:'q',
							cachename:_that.customerIdCache
						}
					},null,mainData)
					
					if(_that.subEditorObj["title1"]){
						let attr = {
							showAdd:true,
							showDel:true,
							getWorkParam:'getWorkParam',
						}
						let configData = _that.subConfigData['title1']
						if(hasEditor("title1","customerProductName",configData)){
							let title = getEditorTitle("title1","customerProductName",configData)
							attr.titleTemplate = title+':<%= customerProductName || "无" %>'
						}
						changeEditor("title1","dataStr",attr,mainData)
					}
						if(fileId){
							let fieldArr = getFormFields(mainData)
							fieldArr.push('id','customerCode')
							for(let index in res[8].value){
								if(fieldArr.includes(index)){
									if(index == 'customerCode'){
										_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'customerShowId',res[8].value[index])
										_that.$set(_that.formdata,'customerShowId',res[8].value[index])
									}
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[8].value[index])
									_that.$set(_that.formdata,index,res[8].value[index])
								}
							}
							uni.setStorageSync('oldWorkList', JSON.stringify(res[8].value.dataList))
							if(_that.subEditorObj['title1']){
								let dataList = res[8].value.dataList
								_that.subEditorObj['title1'].workList = dataList
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,'dataStr',JSON.stringify(dataList))
								_that.$set(_that.formdata,'dataStr',JSON.stringify(dataList))
							}
							
							changeEditor("title2","businessOwnerId",{
								link:'../../public/pageSearch/pageSearch',
								"linkParam":{
									other:JSON.stringify({
										firstUserId:res[8].value.businessOwnerId
									}),
									url:'temployee/getStaf fCombogrid',
									namefield:'userPosInstName',
									initload:true,
									searchfield:'q',
									cachename:_that.businessOwnerIdCache
								}
							},null,mainData)
							if(res[8].value.businessOwnerId){
								_that.om.request(
									'temployee/getUserPosAddSalary',
									{
										userId: res[8].value.businessOwnerId
									}
								,'post').then(res=>{
									_that.$refs.autoform.changeEditor("title2","businessInstId","data",configSelectData([res.value],"id","salaryPosInstName"))
									_that.$refs.autoform.initSelectIndex("title2","businessInstId")
								})
							}
							changeEditor("title2","customerId",{
								link:'../../public/pageSearch/pageSearch',
								"linkParam":{
									other:JSON.stringify({
										firstId:res[8].value.customerId
									}),
									url:'customerShow/getCustomerPageTwo',
									namefield:'customerId',
									notefield:'customerName',
									initload:true,
									searchfield:'q',
									cachename:_that.customerIdCache
								}
							},null,mainData)
						}
					_that.$nextTick(function(){
						if(_that.$refs.autoform){
							_that.$refs.autoform.initSelectIndex("title","communicateWayId")
							_that.$refs.autoform.initSelectIndex("title","communicateResultId")
							_that.$refs.autoform.initSelectIndex("title","lateServiceTypeId")
							if(_that.formdata.communicateUserId){
								_that.findInstByUserIdOrPostId(_that.formdata.communicateUserId)
							}
						}
					})
				}, options)
			},
			formSubmit() {
				let _that = this
				if(_that.subEditorObj["title1"]){
					let dataList = JSON.parse(_that.formdata.dataStr)
					for(let item of dataList){
						if(!item.fileList){
							delete item.fileList
						}
					}
					_that.formdata.dataStr = JSON.stringify(dataList) 
				}
				if(this.checkedit) {
					_that.om.formSave('commonForm/doCheckOrApproveUpdate', _that.formdata, _that)
				} else if(this.edit){
					_that.om.formSave("serviceCommunication/doUpdate",_that.formdata,_that)
				} else {
					_that.om.formSave("serviceCommunication/doAdd",_that.formdata,_that)
				} 
			}
		},
		onUnload(){
		//#ifdef APP-PLUS
			let _that = this;
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
		//#endif
		},
		onLoad(options) {
			this.initValue.userinfoId = this.userId
			this.initLoad(options)
		},
		onShow() {
			let _that = this;
			if (_that.$refs.autoform) {
				for (var fieldId in _that.subEditorObj) {
					var editor = _that.subEditorObj[fieldId];
					uni.getStorage({
						key: getWorkCacheKey(fieldId),
						success: function(res) {
							editor.workList = res.data;
							for(let item of editor.workList){
								let communicateResultId = _that.$refs.autoform.formdata.communicateResultId
								let lateServiceTypeId = _that.$refs.autoform.formdata.lateServiceTypeId
								if(!item.communicateResultId || communicateResultId !=item.communicateResultId){
									_that.$refs.autoform.clear("title","communicateResultId")
								}
								if(!item.lateServiceTypeId || lateServiceTypeId !=item.lateServiceTypeId){
									_that.$refs.autoform.clear("title","lateServiceTypeId")
								}
							}
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					});
				}
			}
			uni.getStorage({
				key:_that.communicateUserIdCache,
				success:(res)=>{
					if(res.data){
						let d = res.data[0]
						let formdata = _that.$refs.autoform.formdata
						formdata.communicateUserId = d.id
						formdata.communicateUserName = d.username
						formdata.communicateInstId = d.posInfos[0].instId
						formdata.communicateInstName = d.posInfos[0].instName
						_that.findInstByUserIdOrPostId(d.id)
						uni.removeStorage({
							key:_that.communicateUserIdCache
						})
					}
				}
			})
			uni.getStorage({
				key:_that.customerCache,
				success:(res)=>{
					if(res.data){
						let d = res.data
						let formdata = _that.$refs.autoform.formdata
						formdata.customerId = d.id
						formdata.customerCode = d.customerId
						formdata.customerName =  d.customerName
						uni.removeStorage({
							key:_that.customerCache
						})
					}
				}
			})
			uni.getStorage({
				key:_that.businessOwnerCache,
				success:(res)=>{
					if(res.data){
						let d = res.data[0]
						let formdata = _that.$refs.autoform.formdata
						formdata.businessOwnerId = d.id
						formdata.businessOwnerName = d.username
						formdata.businessInstId = d.posInfos[0].instId
						formdata.businessInstName = d.posInfos[0].instName
						uni.removeStorage({
							key:_that.businessOwnerCache
						})
					}
				}
			})
			try {
				const value = uni.getStorageSync('chooseData');
				if (value) {
					let obj = {}
					let arr= []
					let name = ''
					let codes = []
					let sourceFormId = ''
					let formdata = _that.$refs.autoform.formdata
					formdata.repairReportUserId = value[0].zauserId
					formdata.repairReportUserName = value[0].zauserName
					formdata.repairReportInstId = value[0].zinstId
					formdata.repairReportInstName = value[0].zinstName
					formdata.repairReportTime = value[0].ztime
					formdata.businessOwnerId = value[0].businessOwnerId
					formdata.businessOwnerName = value[0].businessOwnerName
					formdata.businessInstId = value[0].businessInstId
					formdata.businessInstName = value[0].businessInstName
					formdata.askTypeId = value[0].askTypeId
					formdata.askTypeName = value[0].askTypeName
					formdata.customerId = value[0].customerId
					formdata.customerCode = value[0].customerCode
					formdata.customerName = value[0].customerName
					formdata.customerContactId = value[0].customerContactId
					formdata.customerContactName = value[0].customerContactName
					formdata.customerContactPhone = value[0].customerContactPhone
					formdata.useCompany = value[0].useCompany
					formdata.useCompanyContact = value[0].useCompanyContact
					formdata.useCompanyContactPhone = value[0].useCompanyContactPhone
					formdata.locationId = value[0].locationId
					formdata.locationName = value[0].locationName
					formdata.userCompanyAddress = value[0].userCompanyAddress
					formdata.askDesperation = value[0].askDesperation
					formdata.expectFinishDate = value[0].expectFinishDate
					for(let item of value){
						name = item.busName
						sourceFormId = item.id 
						codes.push(item.code)
						for(let subItem of item.subData){
							arr.push(subItem)
						}
					}
					formdata.sourceFormCode = codes.map(e=> e).join(',')
					formdata.sourceFormName = name
					formdata.sourceFormId = sourceFormId
					if(_that.subEditorObj["title1"]){
						_that.subEditorObj["title1"].workList = arr
					}
					uni.removeStorageSync('chooseData')
				}
			} catch (e) {
				// error
			}
		}
	}
</script>

<style>
</style>
